package com.ruoyi.app.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.ijpay.alipay.AliPayApi;
import com.ijpay.alipay.AliPayApiConfigKit;
import com.ruoyi.app.config.AliPay;
import com.ruoyi.app.model.vo.LoginReq;
import com.ruoyi.app.model.vo.RechargeReq;
import com.ruoyi.app.service.OrderService;
import com.ruoyi.app.service.PayService;
import com.ruoyi.common.annotation.PassToken;
import com.ruoyi.common.core.domain.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Api(value = "支付相关", tags = "支付相关接口")
@RestController
@RequestMapping("/api/pay")
@Slf4j
public class PayController {


    @Autowired
    private PayService payService;


    @Autowired
    private OrderService orderService;


    @ApiOperation("套餐列表")
    @GetMapping("/package-list")
    public AjaxResult packageList() {
        return AjaxResult.success(payService.packageList());
    }


    @ApiOperation("充值套餐")
    @PostMapping("/recharge")
    public AjaxResult recharge(@RequestBody @Validated RechargeReq req) {
        AliPay.initAliPay();
        return AjaxResult.success(payService.recharge(req));
    }


    @RequestMapping(value = "/ali_pay/notify_url")
    @ResponseBody
    @PassToken
    public String notifyUrl(HttpServletRequest request) {
        log.info("支付宝回调！");
        AliPay.initAliPay();
        try {
            // 获取支付宝POST过来反馈信息
            Map<String, String> params = AliPayApi.toMap(request);
            for (Map.Entry<String, String> entry : params.entrySet()) {
                log.info("支付宝回调参数" + entry.getKey() + " = " + entry.getValue());
            }
            boolean verifyResult = AlipaySignature.rsaCheckV1(params, AliPayApiConfigKit.getAliPayApiConfig().getAliPayPublicKey(), "UTF-8", "RSA2");
            if (verifyResult) {
                // TODO 请在这里加上商户的业务逻辑程序代码 异步通知可能出现订单重复通知 需要做去重处理
                String orderId = params.get("out_trade_no");
                double money = Double.parseDouble(params.get("total_amount"));
                return orderService.processingOrder(orderId, money) ? "success" : "failure";

            } else {
                System.out.println("notify_url 验证失败");
                // TODO
                return "failure";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return "failure";
        }
    }


}
